<template>
	<view>
		<j-cell-group>
		    <j-cell title="国家/地区" :tips="country" :is-tap="true" :more="true" @jftap="onBindtapAllRegion()"></j-cell>
		    <j-cell v-if="code == 'CN'" title="详细地址"  :is-tap="false" :more="true" style="position: relative;">
				<view slot="tips">
					<!-- v-if="location" -->
					<view>
						<picker
                            class="j-picker"
                            mode="multiSelector"
                            range-key="name"
                            @columnchange="bindMultiPickerColumnChange"
                            :value="multiIndex"
                            :range="multiArray"
                            @change="pickerChange"
                            @cancel="cancelPicker"
                        >
							<view class="detail">
                                <text>{{location}}</text>
                            </view>
						</picker>
					</view>
				</view>
			</j-cell>
		</j-cell-group>
		<view class="find-food">
		    <button class="radius-btn" type="operation" @click="saveLoaction">保存</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				code:'',
				country:'',
				location:'',
				group:{},
				multiArray: [],
                locationArray: [],
				multiIndex: [0, 0, 0],
				provinceList:[],
                valueList: [],
				value:''
			}
		},
		onUnload() {
			uni.$off('chooseArea')
		},
		onLoad(options) {
			let group = JSON.parse(options.group);
			console.log('group==',group);
			this.group = group
			if(this.group.location){
                // this.locationFn(this.group.location)
				let arr = this.group.location.split('-')
				this.country = arr[0]
				this.code = arr[arr.length-1]
				if(this.code == 'CN'){
					arr.splice(arr.length-1,1)
					arr.splice(0,1)
					this.location = arr.join(' ');
				}
                if(arr.length < 3 && arr.length > 1) {
                    arr.unshift(arr[0])
                }
                this.locationArray = arr
			} else {
                const location = '中国-北京市-CN'
                this.locationFn(location)
            }
			this.getAllArea()
			this.getChooseArea()
		},
		onShow() {
			
		},
		methods: {
            // 直辖市去重
            handleFn(province, city, area) {
                if(province == city) {
                    this.location = city + ' ' + area
                } else {
                    this.location = province + ' ' + city + ' ' + area
                }
                if(!city&&!area) {
                    // 特别行政区处理
                    this.location = province
                }
            },
            // 点击取消是触发
            cancelPicker(e) {
                this.multiIndex = [...this.valueList]
                const obj = {
                    code: '',
                    name: ''
                }
                if(this.multiIndex.length) {
                    this.multiArray[1] = this.provinceList[this.multiIndex[0]].children ? this.provinceList[this.multiIndex[0]].children : [obj]
                    this.multiArray[2] = this.provinceList[this.multiIndex[0]].children ? this.provinceList[this.multiIndex[0]].children[this.multiIndex[1]].children : [obj]
                }
            },
            // picker改变触发
            pickerChange(e) {
                const arr = e.detail.value
                this.valueList = arr
                const province = this.multiArray[0][arr[0]].name
                this.handleFn(this.multiArray[0][ arr[0]].name, this.multiArray[1][ arr[1]].name, this.multiArray[2][ arr[2]].name)
                // this.location = this.multiArray[0][ arr[0]].name +' '+ this.multiArray[1][ arr[1]].name +' '+ this.multiArray[2][ arr[2]].name
            },
            // 家庭位置处理方法
            locationFn(list) {
                let arr = list.split('-')
                this.country = arr[0]
                this.code = arr[arr.length-1]
                if(this.code == 'CN'){
                    arr.splice(arr.length-1,1)
                    arr.splice(0,1)
                    this.location = arr.join(' ');
                }
            },
			// 获取选择地址
			getChooseArea(){
				uni.$on('chooseArea',(res)=>{
					if(res){
						this.$nextTick(()=>{
							this.code = res.data.code
							this.country = res.data.name
                            if(res.data.code === 'CN') {
                                this.multiIndex = [0]
                                this.location = this.multiArray[0][ this.multiIndex[0]].name
                            }
                        })
					}
				})
			},
			//保存位置
			saveLoaction(){
				if(!this.country){
					uni.showToast({
						title:'请选择国家或地区',
						icon:'none'
					})
					return
				}
				let location = this.country+'-'+this.code
				if(this.code == 'CN'){
					let str  = this.location.replace(/ /g,'-')
					console.log('str=========',str);
					location = this.country+'-'+ str +'-'+this.code;
				}
				let data = {
				    id: this.group.id,
				    location: location
				};
				getApp().globalData.api.updateUserGroup(data, (result) => {
					uni.showToast({
						title:'保存成功',
						icon:'none'
					})
				    uni.navigateBack({ });
				});
			},
			// 选择国家/地区
			onBindtapAllRegion(){
				uni.navigateTo({
					url: `/jvss/pagesDevice/group/allArea/allArea`
				})
			},
			//详细地址
			onBindtapGroupDetailLocation(){
				uni.navigateTo({
					url: `/jvss/pagesDevice/group/group-area/group-area`
				})
			},
			//切换地区
			bindMultiPickerColumnChange(e){
				let detail = e.detail
				let column = detail.column
				let value = detail.value
				this.multiIndex[e.detail.column] = e.detail.value
                const obj = {name: '',code: ''}
				if(column == 0){
					let index = this.multiIndex[0]
					this.multiIndex = [value,0,0]
					this.multiArray[1] = this.provinceList[index].children ? this.provinceList[index].children : [obj]
					this.multiArray[2] = this.provinceList[index].children ? this.provinceList[index].children[0].children : [obj]
				}
				if(column == 1){
					let index = this.multiIndex[0]
					this.multiIndex[2] = 0
					let i = this.multiIndex[0]
					this.multiArray[2] = this.provinceList[i].children[value].children
				}
				// this.location = this.multiArray[0][ this.multiIndex[0]].name +' '+ this.multiArray[1][ this.multiIndex[1]].name +' '+ this.multiArray[2][ this.multiIndex[2]].name
				this.$forceUpdate()
			},
			//获取中国所有地区
			getAllArea() {
				uni.showLoading({
					title:'加载中'
				})
			    getApp().globalData.api.getAllArea((result) => {
			        // console.log('获取所有地区:', result); 
					// result.region.forEach(item => {
			        // if(item.Code === 'CN'){
					uni.hideLoading()
					this.provinceList = result
			        let province = result; //item.children
			        let city;
			        let area;
			        let value = [];
					let locationArray = []
					if(this.location){
						 this.location.split(' ');
					}
                    city = province[0].children;
                    area = province[0].children[0].children;
                    // value = [0, 0, 0];
			        if (this.locationArray.length > 1) {
			            for (let i = 0; i < province.length; i++) {
			                const item = province[i];
			                if (item.name === this.locationArray[0]) {
			                    console.log('某个省对象：', item, i);
			                    value.push(i);
			                    city = item.children;
			                    console.log('市列表：', city);
								if(item.children && item.children.length > 0){
									for (let j = 0; j < item.children.length; j++) {
									    const pro = item.children[j];
									    if (pro.name === this.locationArray[1]) {
									        console.log('某个市对象：', pro);
									        value.push(j);
									        area = pro.children;
									        console.log('县区列表：', area);
											if(pro.children && pro.children.length > 0){
												for (let m = 0; m < pro.children.length; m++) {
												    const obj = pro.children[m];
																				
												    if (obj.name === this.locationArray[2]) {
												        console.log('某个区对象：', obj);
												        value.push(m);
												        console.log('街列表：', obj.children); // break
												    }
												} // break
											}else{
												value.push(0)
											}
									    }
									} // break
								}else{
									value.push(0)
									value.push(0)
								}
			                }// end if
			            }// end for
			        }
                    // else {
			        //     city = province[0].children;
			        //     area = province[0].children[0].children;
			        //     value = [0, 0, 0];
			        // }

                    this.valueList = [...value]
                    this.multiIndex = value
					this.province = province
					this.city = city
					this.area = area
					this.multiArray[0] = province,
					this.multiArray[1] = city
					this.multiArray[2] = area
					if(!this.location){
                        if(this.code == 'CN') {
                            this.handleFn(this.multiArray[0][ this.multiIndex[0]].name, this.multiArray[1][ this.multiIndex[1]].name, this.multiArray[2][ this.multiIndex[2]].name)
                            // this.location = this.multiArray[0][ this.multiIndex[0]].name +' '+ this.multiArray[1][ this.multiIndex[1]].name +' '+ this.multiArray[2][ this.multiIndex[2]].name
                        } else {
                            console.log(this.multiArray, '国外');
                        }

                    }
					this.$forceUpdate()
					// console.log('省市区===1',province);
					// console.log('省市区===2',city);
					// console.log('省市区===3',area);
					this.$nextTick(()=>{
						this.value = value
					}) // }
			        // })
			    });
			},
			
		}
	}
</script>

<style>
.detail{
    width: 100%;
	font-size: 24rpx;
	color: #999;
    text-align: right;
}
.detail text {
    margin-right: 62rpx;
}
.find-food {
	text-align: center;
	position: fixed;
	bottom: 50rpx;
	width: 100%;
	font-size: 28rpx;
}
.j-picker {
    position: absolute;
    width: calc(100vw - 20px);
    height: 46.6px;
    line-height: 46.6px;
    left: 0;
    top: 0;
    //transform: translateY(-50%);
}
</style>
